﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Blog_BLL;
using System.Collections;
using System.Net;
using System.IO;
using System.Text;
using System.IO.Compression;

namespace Blog_UI.Controllers
{


    public class HomeController : Controller
    {
        [CompressFilter]
        // GET: Home
        public ActionResult Index()
        {
            Blog_MODEL.BlogArticle _BlogArticle = Blog_BLL.BlogArticleBLL.getObenBlogArticle();
            _BlogArticle.BlogArticleBody = _BlogArticle.BlogArticleBody.ReplaceHtmlTag(100);
            return View(_BlogArticle);
        }
        [CompressFilter]
        public ActionResult About()
        {
            return View();
        }
        [CompressFilter]
        public ActionResult message()
        {
            //获取前十博客文章
            var listBlogArticle = Blog_BLL.PagingBLL.getPages<Blog_MODEL.BlogArticle>(10, 1, "BlogArticleSortValue desc,BlogArticleBrowsingNum desc", "BlogArticle");
            List<Blog_MODEL.BlogArticle> _listBlogArticle = listBlogArticle["data"] as List<Blog_MODEL.BlogArticle>;
            return View(_listBlogArticle);
        }
        public ActionResult zuozhe()
        {
            return View();
        }
        public ActionResult searchtop()
        {
            return View();
        }
        [ChildActionOnly]
        public ActionResult left()
        {
            //获取前十博客文章
            var listBlogArticle = Blog_BLL.PagingBLL.getPages<Blog_MODEL.BlogArticle>(10, 1, "BlogArticleSortValue desc,BlogArticleBrowsingNum desc", "BlogArticle");
            //获取前十热门博客标签
            var listBlogLable = Blog_BLL.PagingBLL.getPages<Blog_MODEL.BlogLable>(15, 1, "BlogLableSortValue desc,BlogLableClicks desc", "BlogLable");

            List<Blog_MODEL.BlogArticle> _listBlogArticle = listBlogArticle["data"] as List<Blog_MODEL.BlogArticle>;
            List<Blog_MODEL.BlogLable> _listBlogLable = listBlogLable["data"] as List<Blog_MODEL.BlogLable>;
            Blog_MODEL.BlogArticle _BlogArticle = Blog_BLL.BlogArticleBLL.getObenBlogArticle();
            _BlogArticle.BlogArticleBody = _BlogArticle.BlogArticleBody.ReplaceHtmlTag(100);
            return View(Tuple.Create(_listBlogArticle, _listBlogLable, _BlogArticle));
        }
        /// <summary>
        /// 首页分页获取博客
        /// </summary>
        /// <returns></returns>
        public string getBlogArticleData()
        {
            string strReulst = null;
            Int32 PageIndex = string.IsNullOrEmpty(Request.QueryString["PageIndex"]) ? 0 : Convert.ToInt32(Request.QueryString["PageIndex"]);
            Int32 PageSize = string.IsNullOrEmpty(Request.QueryString["PageSize"]) ? 0 : Convert.ToInt32(Request.QueryString["PageSize"]);
            String SearchBlog = string.IsNullOrEmpty(Request.QueryString["searchblog"]) ? "" : Request.QueryString["searchblog"];
            Int32 BlogLable = string.IsNullOrEmpty(Request.QueryString["bloglablebh"]) ? 0 : !System.Text.RegularExpressions.Regex.IsMatch(Request.QueryString["bloglablebh"], @"^[+-]?/d*$") ? Convert.ToInt32(Request.QueryString["bloglablebh"]) : 0;
            //自定义博客结果列
            string strColumns = @"( select STUFF(( SELECT ','+B.BlogLableName FROM (SELECT B.BlogLableName FROM BlogLable B WHERE 
                                                    exists(
                                                    SELECT B1.BlogRelateLableId FROM BlogRelated B1
                                                    where B.BlogLableBh=B1.BlogRelateLableId
                                                AND B1.BlogRelatedArticleId=BA.Id)) B  FOR XML PATH('')),1,1,'')) as BlogLableNames,
                                                BA.BlogArticleTitle,
                                                BA.BlogArticleCreateTime,
                                                BA.BlogArticleBrowsingNum,
                                                BA.BlogArticleLikeNum,BA.BlogArticleCommentNum,
                                                BA.BlogArticleBody,BA.BlogArticleBody_Markdown,BA.Id";
            string strWhere = null;
            if (!string.IsNullOrEmpty(SearchBlog))
                strWhere += string.Format(@" UPPer(A.BlogArticleTitle) like '%{0}%' or
                                             A.BlogArticleBody like '%{0}%' or
                                             A.BlogArticleBody_Markdown like '%{0}%'", SearchBlog.Filter().ToUpper());
            if (BlogLable != 0)
            {
                strWhere += string.Format(@"EXISTS(
                        SELECT BlogRelatedArticleId FROM (SELECT BlogRelatedArticleId FROM BlogRelated WHERE BlogRelateLableId={0}) BR
                        WHERE BR.BlogRelatedArticleId=A.Id
                        )", BlogLable);
            }
            var listBlogArticle = Blog_BLL.PagingBLL.getPages<Blog_MODEL.BlogArticle>(PageSize, PageIndex, "BlogArticleCreateTime desc", "BlogArticle BA", strWhere == null ? " 1=1 " : strWhere, strColumns);
            ArrayList alist = new ArrayList();
            foreach (var blog in listBlogArticle["data"] as List<Blog_MODEL.BlogArticle>)
            {
                string BlogImg = blog.BlogArticleBody.GetHtmlImageUrlList().Length == 0 ? "../Content/images/blogimg/" + new Random(Guid.NewGuid().GetHashCode()).Next(1, 21).ToString() + ".jpg" : blog.BlogArticleBody.GetHtmlImageUrlList()[0];//匹配HTML里面的img标签取第一个当做此博客的图片
                alist.Add(new
                {
                    Id = blog.Id,
                    BlogArticleTitle = blog.BlogArticleTitle,
                    BlogArticleBody = blog.BlogArticleBody.ReplaceHtmlTag(100),
                    BlogArticleCreateTime = blog.BlogArticleCreateTime,
                    BlogArticleLikeNum = blog.BlogArticleLikeNum,
                    BlogArticleBrowsingNum = blog.BlogArticleBrowsingNum,
                    BlogArticleCommentNum = blog.BlogArticleCommentNum,
                    BlogLableNames = blog.BlogLableNames,
                    BlogImg = BlogImg
                });
            }
            listBlogArticle["data"] = alist;
            if (listBlogArticle.Count > 0)
            {
                strReulst = Blog_BLL.JsonHelper.ResponseData(Blog_BLL.StateCode.success, "获取成功", Blog_BLL.JsonHelper.ToJsonData(listBlogArticle));
            }
            else
            {
                strReulst = Blog_BLL.JsonHelper.ResponseData(Blog_BLL.StateCode.failure, "获取失败", "[]");
            }
            return strReulst;
        }
        /// <summary>
        /// 博客详情页
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [CompressFilter]
        public ActionResult show(int? id)
        {
            List<Blog_MODEL.BlogArticle> List = null;
            Blog_MODEL.BlogArticle _BlogArticle = null;
            if (id != null)
            {
                System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(id.Value.ToString());
                //有人浏览文章就调用畅言接口获取文章评论数等信息
                string jsonData = getchangyanData(id.Value.ToString());
                jsonData = r.Replace(jsonData, "obj", 1);
                Rootobject rb = JsonHelper.ToJsonObject<Rootobject>(jsonData);
                int Id = id == null ? 0 : (Int32)id;
                List = Blog_BLL.BlogArticleBLL.getBlogArticleShow(Id);
                _BlogArticle = List[0];
                _BlogArticle.BlogArticleBrowsingNum = List[0].BlogArticleBrowsingNum + 1;
                _BlogArticle.BlogArticleLikeNum = rb.result.obj.likes;
                _BlogArticle.BlogArticleCommentNum = rb.result.obj.comments;
                Blog_BLL.BlogArticleBLL.addBrowsingNum(_BlogArticle);
            }
            if (List == null)
                return RedirectToAction("Index", "Error");
            if (List.Count(t => t.Id == id) == 0)
                return RedirectToAction("Index", "Error");
            return View(Tuple.Create(List));
        }
        private string getchangyanData(string Id)
        {
            string serviceAddress = "http://changyan.sohu.com/api/2/topic/count?client_id=cytyPBtWx&topic_source_id=" + Id;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress);
            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
            return retString;
        }
        public class Rootobject
        {
            public Result result { get; set; }
        }

        public class Result
        {
            public obj obj { get; set; }
        }

        public class obj
        {
            public int comments { get; set; }
            public long id { get; set; }
            public int likes { get; set; }
            public int parts { get; set; }
            public int shares { get; set; }
            public string sid { get; set; }
            public int sum { get; set; }
        }

    }
    /// <summary>
    /// 网页压缩
    /// </summary>
    public class CompressFilterAttribute : ActionFilterAttribute
    {
        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            string acceptEncoding = filterContext.HttpContext.Request.Headers["Accept-Encoding"];
            if (String.IsNullOrEmpty(acceptEncoding)) return;
            var response = filterContext.HttpContext.Response;
            acceptEncoding = acceptEncoding.ToUpperInvariant();
            if (acceptEncoding.Contains("GZIP"))
            {
                response.AppendHeader("Content-Encoding", "gzip");
                response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
            }
            else if (acceptEncoding.Contains("DEFLATE"))
            {
                response.AppendHeader("Content-Encoding", "deflate");
                response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
            }
        }
    }
}